home *** CD-ROM | disk | FTP | other *** search
- Path: news.reed.edu!usenet
- From: Peter Folk <pfolk@uni.uiuc.edu>
- Newsgroups: comp.lang.c++
- Subject: How to: friend template function
- Date: Wed, 24 Jan 1996 18:18:34 -0500
- Organization: Reed College, Portland, Oregon
- Message-ID: <3106BE4A.2DF8@uni.uiuc.edu>
- NNTP-Posting-Host: 134.10.17.160
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b6a (Macintosh; I; PPC)
-
- Hey,
-
- While working on my most current project, I needed to implement some
- socket communication. So, I took my normal C socket routines, got
- my file descriptor, and attach()ed it to a Server class that inherited
- from fstream. Unfortunately, for some reason this was disasterous...
- hanging up the connection at odd times, not recieving the input the
- server sent, etc, etc, so after a lot of fooling, I figured out that
- it worked if I had separate in and out streams. Thanks to my attempts
- at OOP (ie a hidden implementation), I expeced this to be an easy
- change... all I had to do was redefine Server:
-
- class Server : public fstream {
- fstream io;
- // ...
- }
-
- to
-
- class Server {
- ifstream in;
- ofstream out;
- // ...
- public:
- Server &operator<<(/* each type I need */);
- Server &operator>>(/* each type I need */);
- }
-
-
- And then it occurred to me that I should just make the >> and <<
- operators templates:
-
- template <class T>
- Server &operator<<(Server &s, T &t)
- {
- s.out<<t; return *this;
- }
-
- template <class T>
- Server &operator>>(Server &s, T &t)
- {
- s.in>>t; return *this;
- }
-
-
-
- But, whoops! I needed to give >> and << access to in and out
- so Server turns into:
-
- class Server {
- friend template <class T> Server &operator<<(Server &, T &);
- friend template <class T> Server &operator>>(Server &, T &);
-
- ifstream in;
- ofstream out;
- // ...
- }
-
-
-
- Now, my question is, why does my compiler complain so violently
- about that, and is there a way to do this without declaring in
- and out public?
-
-
- Thanks for any help,
- Peter Folk
-
-
- p.s. If anyone knows why the fstream inheritance wasn't working, I'd
- love to hear about that, too.
-
- p.p.s. If there's something fundamentally bad about what I'm doing,
- that would be nice to know, too... I've been programming C++ for,
- oh, at least a month now, so I really expect my code to be perfect
- (sarcasm).
-